package com.starhub.integration.sdk.baidu.core;

import okhttp3.OkHttpClient;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * 百度向量模型连接器
 */
@Component
public class BaiduClientConnector {
    private static OkHttpClient okHttpClient;
    private static final Map<String, BaiduClient> clientMap = new ConcurrentHashMap<>();
    private static final Map<String, TokenInfo> tokenCache = new ConcurrentHashMap<>();

    // token缓存时间设置为29天（百度token有效期为30天）
    private static final long TOKEN_CACHE_TIME = 29 * 24 * 60 * 60 * 1000L;

    private synchronized OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .build();
        }
        return okHttpClient;
    }
    
    /**
     * 获取百度向量化模型客户端
     * @param mark
     * @param apiKey
     * @param secretKey
     * @return
     */
    public synchronized BaiduClient getBaiduClient(String mark, String apiKey, String secretKey) {
        String clientKey = mark + "_" + apiKey;
        TokenInfo tokenInfo = tokenCache.get(clientKey);
        BaiduClient client = clientMap.get(clientKey);

        // 如果client不存在或token已过期，则重新获取
        if (client == null || System.currentTimeMillis() - tokenInfo.getCreateTime() > TOKEN_CACHE_TIME) {
            client = BaiduClient.builder()
                    .okHttpClient(getOkHttpClient())
                    .apiHost("https://aip.baidubce.com")
                    .apiKey(apiKey)
                    .secretKey(secretKey)
                    .build();

            // 初始化token
            String token = getOrRefreshToken(mark, apiKey, secretKey);
            client.setAccessToken(token);

            clientMap.put(clientKey, client);
        }

        return client;
    }

    /**
     * 获取或刷新token
     * @param mark
     * @param apiKey
     * @param secretKey
     * @return
     */
    private String getOrRefreshToken(String mark, String apiKey, String secretKey) {
        String tokenKey = mark + "_" + apiKey;
        TokenInfo tokenInfo = tokenCache.get(tokenKey);

        try {
            BaiduClient tempClient = BaiduClient.builder()
                    .okHttpClient(getOkHttpClient())
                    .apiHost("https://aip.baidubce.com")
                    .apiKey(apiKey)
                    .secretKey(secretKey)
                    .build();

            String newToken = tempClient.getAccessToken();
            tokenInfo = new TokenInfo(newToken, System.currentTimeMillis());
            tokenCache.put(tokenKey, tokenInfo);
        } catch (Exception e) {
            throw new RuntimeException("获取百度token失败", e);
        }

        return tokenInfo.getToken();
    }

    /**
     * Token信息内部类
     */
    private static class TokenInfo {
        private final String token;
        private final long createTime;

        public TokenInfo(String token, long createTime) {
            this.token = token;
            this.createTime = createTime;
        }

        public String getToken() {
            return token;
        }

        public long getCreateTime() {
            return createTime;
        }
    }
}